<template>
  <div>
    <div class="button-list">
      <Button icon="plus" shape="circle" type="primary" @click="showEditWin(-1)">添加</Button>
      <Button icon="refresh" shape="circle" type="warning" @click="getUserList">刷新</Button>
    </div>
    <div class="data-list">
      <Table border stripe :columns="columns" :data="this.$store.state.userList" size="small"></Table>
    </div>
    <Modal v-model="isEdit" title="编辑" :mask-closable="false">
      <Form ref="user" :model="userinfo" :label-width="80">
        <FormItem prop="uid" label="UID" :rules="{required: true, message: '请输入用户ID'}">
          <Input type="text" v-model="userinfo.uid" placeholder="请输入用户ID"></Input>
        </FormItem>
        <FormItem prop="username" label="账号" :rules="{required: true, message: '请输入用户账号'}">
          <Input type="text" v-model="userinfo.username" placeholder="请输入用户账号"></Input>
        </FormItem>
        <FormItem prop="nickname" label="昵称" :rules="{required: true, message: '请输入用户昵称'}">
          <Input type="text" v-model="userinfo.nickname" placeholder="请输入用户昵称"></Input>
        </FormItem>
        <FormItem label="脸模">
          <Button type="primary" @click="isBindFace=true">{{face_img?'修改脸模':'绑定脸模'}}</Button>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="postData('user')">保存</Button>
      </div>
    </Modal>
    <Modal v-model="isBindFace" title="绑定脸模" :mask-closable="false" :width="650">
      <Row :gutter="20">
        <Col span="12">
          <face-feature v-if="isEdit" @feature="getFaceFeature"></face-feature>
        </Col>
        <Col span="12">
          <img v-if="face_img" :src="face_img" width="300" height="300">
        </Col>
      </Row>
      <div slot="footer">
        <Button type="primary" @click="faceListener=true">获取人脸特征</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import faceFeature from '@/common/faceFeature/faceFeature'
  import {getUserList, addUser, saveFaceFeature, updateUser, removeUser, FacePairMatching} from '@/common/db/user'
  import {config} from '@/common/utils'

  const softconfig = config.get('softconfig')

  export default {
    name: 'userList',
    data() {
      return {
        isEdit: false,
        isBindFace: false,
        columns: [{
          title: 'UID',
          key: 'uid',
          width: 80
        }, {
          title: '账号',
          key: 'username',
          width: 200
        }, {
          title: '昵称',
          key: 'nickname',
          width: 200
        }, {
          title: '照片',
          key: 'face_img',
          width: 70,
          render: (h, params) => {
            return h('img', {
              attrs: {
                width: 30,
                height: 30,
                src: `${params.row.face_img}?${Date.parse(new Date())}`
              }
            })
          }
        }, {
          title: '脸模路径',
          key: 'face_dat'
        }, {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.showEditWin(params.index)
                  }
                }
              }, '修改'), h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.remove(params.index)
                  }
                }
              }, '删除')
            ])
          }
        }],
        userinfo: {},
        face_dat: null,
        face_img: '',
        faceListener: false,
        isAdd: true
      }
    },
    methods: {
      getFaceFeature(data) {
        if (this.faceListener) {
          this.face_dat = data.faceFeatureCopy
          this.face_img = data.data
          this.faceListener = false
        }
      },
      // 比较特征库
      facePairMatching() {
        // 脸模是否存在
        this.isExist = false
        let maxScore = 0
        let _list = this.$store.state.userList
        if (!_list.length) {
          this.$Message.success('脸模绑定成功')
          return
        }
        _list.forEach((val, index) => {
          FacePairMatching(this.$store.state.hFREngine, val.faceFeature, this.face_dat, index).then(ret => {
            if (ret.score >= maxScore) {
              maxScore = ret.score
              if (maxScore >= softconfig.threshold / 100 && val._id !== this.userinfo._id) {
                this.isExist = true
                this.$Message.error(`该用户已被（${val.username}）注册`)
              } else {
                this.$Message.success('脸模绑定成功')
              }
            }
          }).catch(e => {
            this.$Message.error(`对比特征库失败，请重试，${e}`)
          })
        })
      },
      postData(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            if (this.isAdd) {
              this.addUser()
            } else {
              this.updateUser()
            }
          }
        })
      },
      getUserList() {
        getUserList().then(list => {
          this.$store.commit('setUserList', list)
        }).catch(e => {
          this.$Message.error(`获用户列表出错,${e}`)
        })
      },
      addUser() {
        if (!this.face_img || !this.face_dat) {
          this.$Message.error('请绑定人脸特征')
          return
        }
        if (this.isExist) {
          this.$Message.error('人脸特征已存在')
          return
        }
        let doc = this.userinfo
        delete doc.face_img
        delete doc.face_dat
        addUser(doc).then(data => {
          this.$Message.success('添加成功')
          this.getUserList()
          this.isEdit = false
          saveFaceFeature(data._id, this.face_dat, this.face_img).then(() => {
            // 添加成功，文件保存成功
            this.face_dat = null
            this.face_img = null
          }).catch(e => {
            this.$Message.error(`文件保存失败:${e}`)
          })
        }).catch(e => {
          this.$Message.error(`添加失败${e}`)
        })
      },
      updateUser() {
        let doc = this.userinfo
        delete doc.face_img
        delete doc.face_dat
        delete doc.faceFeature
        updateUser({_id: this.userinfo._id}, doc).then(num => {
          this.$Message.success(`成功修改${num}条记录`)
          this.getUserList()
          this.isEdit = false
          if (this.face_dat) {
            saveFaceFeature(this.userinfo._id, this.face_dat, this.face_img).then(() => {
              this.face_dat = null
              this.face_img = null
            }).catch(e => {
              this.$Message.error(`文件保存失败:${e}`)
            })
          }
        }).catch(e => {
          this.$Message.error(`修改失败${e}`)
        })
      },
      showEditWin(index) {
        this.isAdd = true
        if (index !== -1) {
          this.isAdd = false
          this.userinfo = this.$store.state.userList[index]
          this.face_img = this.$store.state.userList[index].face_img
        }
        this.isEdit = true
      },
      remove(index) {
        removeUser(this.$store.state.userList[index]).then(num => {
          this.$Message.success(`成功删除${num}条记录`)
          this.getUserList()
        }).catch(e => {
          this.$Message.error(`删除失败${e}`)
        })
      }
    },
    components: {
      faceFeature
    },
    watch: {
      isEdit(val) {
        if (!val) {
          this.userinfo = {}
          this.face_dat = null
          this.face_img = ''
          this.faceListener = false
        }
      },
      faceListener(val) {
        if (!val) {
          this.facePairMatching()
        }
      }
    }
  }
</script>

<style scoped lang="stylus">
  .button-list {
    padding: 14px 16px
  }

  .data-list {
    padding 0 16px
  }
</style>